import React, {Component} from 'react';
import {connect} from 'dva';
import {Button, Card, Col, Form, Input, message, Modal, Popconfirm, Row, Select, Spin, Table, Tooltip} from "antd";
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import {FormattedMessage} from 'umi/locale';
import APP from "@/components/Tool/BaseAPP";
import TinyMCEHandler from "@/components/Tinymce/TinyMCEHandler";

let pagingData = {
    _pageSize: 10,
    _current: 1,
    _total: 0,
};

@connect(({noticeModel, commonModel}) => ({
    noticeModel, commonModel
}))
@Form.create()
class Notice extends Component {
    state = {
        loading: false,
        pageDataSource: [],
        selectedKeys: [],
        isShowEditModal: false,
        editData: {}
    };

    componentDidMount() {
        this.findPageDataSource();
    }

    render() {
        const that = this;
        const {
            loading,
            pageDataSource,
            selectedKeys
        } = that.state;
        const {form} = that.props;
        const {getFieldDecorator} = form;
        return (
            <Spin spinning={loading}>
                <PageHeaderWrapper title={<FormattedMessage id={'menu.settings.notice'} />}>
                    <Card style={{marginBottom: 15}}>
                        <Form layout={'inline'} onSubmit={that.findPageDataSource}>
                            <Row>
                                <Col span={8}>
                                    <Form.Item label="标题">
                                        {getFieldDecorator('title', {})(
                                            <Input placeholder="请输入标题" allowClear={true} />)}
                                    </Form.Item>
                                </Col>
                                <Col span={8}>
                                    <Form.Item label="是否滚动播放">
                                        {getFieldDecorator('scroll', {})(
                                            <Select placeholder={"请选择是否滚动播放"} allowClear={true} style={{width: 174}}>
                                                <Select.Option value="">全部</Select.Option>
                                                <Select.Option value={1}>是</Select.Option>
                                                <Select.Option value={0}>否</Select.Option>
                                            </Select>
                                        )}
                                    </Form.Item>
                                </Col>
                            </Row>
                            <Row>
                                <Col style={{textAlign: 'center', height: '32px', lineHeight: '32px', marginTop: 20}}>
                                    <Button type={"primary"} htmlType={"submit"} {...APP.buttonsStyle_MR15}>
                                        查找
                                    </Button>
                                </Col>
                            </Row>
                        </Form>
                    </Card>
                    <Card style={{marginBottom: 15}}>
                        <Button type={"primary"} {...APP.buttonsStyle_MR15} onClick={() => {
                            that.setState({isShowEditModal: true});
                        }}>
                            新增
                        </Button>
                        <Tooltip title={selectedKeys.length === 1 ? '' : '请选中一行数据'}>
                            <Button type={"primary"} {...APP.buttonsStyle_MR15} onClick={() => {
                                that.getDataById();
                            }}>
                                编辑
                            </Button>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定上架选中数据吗？"
                                onConfirm={() => {
                                    that.enabledControl(1);
                                }}
                                okText="上架"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    上架
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定下架选中数据吗？"
                                onConfirm={() => {
                                    that.enabledControl(0);
                                }}
                                okText="下架"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    下架
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                        <Tooltip title={selectedKeys.length > 0 ? '' : '请选中数据'}>
                            <Popconfirm
                                title="确定删除选中数据吗？"
                                onConfirm={() => {
                                    that.enabledControl(-1);
                                }}
                                okText="删除"
                                cancelText="取消"
                                disabled={!(selectedKeys.length > 0)}
                            >
                                <Button type="primary" {...APP.buttonsStyle_MR15}>
                                    删除
                                </Button>
                            </Popconfirm>
                        </Tooltip>
                    </Card>
                    <Card>
                        <Table
                            bordered
                            rowKey={data => `${data.id}`}
                            rowSelection={APP.tableRowSelection(function (selectedRowKeys, selectedRows) {
                                that.setState({selectedKeys: selectedRowKeys});
                            }, selectedKeys)}
                            columns={that.columns}
                            dataSource={pageDataSource}
                            pagination={{
                                pageSize: pagingData._pageSize,
                                current: pagingData._current,
                                total: pagingData._total,
                                onChange: (page, pageSize) => {
                                    pagingData._current = page;
                                    that.findPageDataSource();
                                },
                                showTotal: total => `共 ${total} 条数据`,
                            }}
                        />
                    </Card>
                    <EditForm parent={that} />
                </PageHeaderWrapper>
            </Spin>
        );
    }

    columns = [{
        title: '发布时间',
        dataIndex: 'createTime',
        key: 'createTime',
    }, {
        title: '标题',
        dataIndex: 'title',
        key: 'title',
    }, {
        title: '状态',
        dataIndex: 'isenabled',
        key: 'isenabled',
    }, {
        title: '是否滚动播放',
        dataIndex: 'scroll',
        key: 'scroll',
    }];

    findPageDataSource = e => {
        let that = this;
        const {form, dispatch} = that.props;
        let params = {...pagingData};
        if (e) {
            pagingData._current = 1;
            e.preventDefault();
        }

        function requestContinue() {
            APP.loading(that);
            dispatch({
                type: "noticeModel/list",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(that);
                    if (data.success) {
                        const {list, pagination} = data.datas;
                        pagingData._current = pagination.current;
                        pagingData._pageSize = pagination.pageSize;
                        pagingData._total = pagination.total;
                        that.setState({
                            pageDataSource: list,
                            selectedKeys: []
                        });
                    }
                }
            });
        }

        form.validateFieldsAndScroll((err, values) => {
            APP.validNilParams(values);
            params = {...params, ...values};
            requestContinue();
        });
    };

    getDataById() {
        const that = this;
        const {selectedKeys} = that.state;
        if (selectedKeys.length !== 1) return;
        const id = selectedKeys[0];
        if (!APP.isValidObj(id)) return;
        const {dispatch} = that.props;
        APP.loading(that);
        dispatch({
            type: "noticeModel/getNoticeById",
            payload: {id: id},
            callback: function (data) {
                that.setState({
                    loading: false,
                    editData: data.datas,
                    isShowEditModal: true
                });
                that.findResponseByUrl(data.datas.content, function(result) {
                    that.contentEditor.setState({
                        content: result,
                    });
                });
            }
        });
    }

    enabledControl(isEnabled) {
        const that = this;
        const {selectedKeys} = that.state;
        if(selectedKeys <= 0) return;
        const {dispatch} = this.props;
        APP.loading(that);
        dispatch({
            type: "noticeModel/enabledControl",
            payload: {
                ids: selectedKeys.join(","),
                isEnabled: isEnabled
            },
            callback: function(data){
                APP.closeLoading(that);
                if(data.success){
                    message.success("操作成功");
                    that.findPageDataSource();
                }else{
                    message.error("操作失败！");
                }
            }
        });
    }

    findResponseByUrl(fileUrl, callback) {
        const that = this;
        const {dispatch} = that.props;
        if (!APP.isValidObj(fileUrl)) {
            APP.closeLoading(that);
            return;
        }
        if (!fileUrl.startsWith('https://')) {
            callback(fileUrl);
            return;
        }
        const formData = new window.FormData();
        formData.append('fileUrl', fileUrl);
        dispatch({
            type: 'commonModel/getResponseByFileUrl',
            payload: formData,
            callback: function(data) {
                if (data.success) {
                    if (APP.isValidObj(callback)) {
                        callback(data.result);
                    }
                } else {
                    APP.errorMessage(data.msg);
                }
            },
        });
    }
}

const EditForm = Form.create()(props => {
    let {parent, form} = props;
    const {loading, isShowEditModal, editData} = parent.state;
    const {getFieldDecorator} = form;
    const {dispatch} = parent.props;
    const formItemLayout = {
        style: {
            margin: '0px',
        },
    };

    function handlerEditModal() {
        form.resetFields();
        let {isShowEditModal, editData} = parent.state;
        isShowEditModal = !isShowEditModal;
        editData = {};
        parent.setState({isShowEditModal, editData});
    }

    function textUpload(text, formType, callback) {
        let formData = new window.FormData();

        formData.append('text', text);
        formData.append('formType', formType);
        formData.append('extension', 'html');

        dispatch({
            type: 'commonModel/fileUploadOfText2',
            payload: formData,
            callback: function(data) {
                if (data.success) {
                    if (APP.isValidObj(callback)) {
                        callback(data);
                    }
                } else {
                    APP.errorMessage(parent, data.msg);
                }
            },
        });
    }

    function submit() {
        function request(params) {
            dispatch({
                type: "noticeModel/saveNotice",
                payload: params,
                callback: function (data) {
                    APP.closeLoading(parent);
                    if (data.success) {
                        message.success("保存成功！");
                        parent.findPageDataSource();
                        handlerEditModal();
                    } else {
                        message.error(data.msg);
                    }
                }
            });
        }

        form.validateFields((err, values) => {
            if (err) return;
            APP.validNilParams(values);
            const contentEditor = parent.contentEditor.editor.editor;
            const content = contentEditor.getContent();
            if (!APP.isValidObj(content)) {
                message.error('请输入公告内容！');
                return;
            }
            APP.loading(parent);
            textUpload(content, 10004, function(contentData) {
                values['content'] = contentData.datas.filePath;
                request(values);
            });
        });
    }

    /**
     * 文件上传
     * @Author 肖家添
     * @Date 2019/8/23 15:49
     */
    function fileUpload(file, formType, callback, failCallback) {
        const formData = new window.FormData();

        formData.append('file', file);
        formData.append('formType', formType);

        dispatch({
            type: 'commonModel/fileUploadOfText',
            payload: formData,
            callback: function(data) {
                if (!data.success) {
                    APP.errorMessage(parent, '图片上传失败');
                    failCallback();
                } else {
                    if (APP.isValidObj(callback)) {
                        callback(data);
                    }
                }
            },
        });
    }

    return (
        <Modal
            title={<FormattedMessage id={'menu.settings.notice.editNotice'} />}
            visible={isShowEditModal}
            onOk={() => submit()}
            onCancel={() => handlerEditModal()}
            okText="保存"
            cancelText='返回'
            confirmLoading={loading}
            width={1000}
        >
            <Form layout={"vertical"}>
                {getFieldDecorator('id', {initialValue: editData.id})(<Input hidden={true} />)}
                <Row>
                    <Form.Item label={'标题'} {...formItemLayout}>
                        {getFieldDecorator('title', {
                            initialValue: editData.title,
                            rules: [
                                {
                                    required: true,
                                    message: '请输入标题',
                                },
                            ],
                        })(<Input placeholder={"请输入标题"} allowClear={true} />)}
                    </Form.Item>
                </Row>
                <Row>
                    <Form.Item label={'是否滚动播放'} {...formItemLayout}>
                        {getFieldDecorator('scroll', {
                            initialValue: APP.changeIsNilVal(editData.scroll, 1),
                            rules: [
                                {
                                    required: true,
                                    message: '请选择是否滚动播放',
                                },
                            ],
                        })(
                            <Select placeholder={"请选择是否滚动播放"} allowClear={true}>
                                <Select.Option value={1}>是</Select.Option>
                                <Select.Option value={0}>否</Select.Option>
                            </Select>
                        )}
                    </Form.Item>
                </Row>
                <Row>
                    <Form.Item label="内容" {...formItemLayout}>
                        <TinyMCEHandler
                            onRef={child => {
                                child.fileUpload = fileUpload;
                                parent.contentEditor = child;
                            }}
                        />
                    </Form.Item>
                </Row>
            </Form>
        </Modal>
    );
});

export default Notice;
